package com.gavin.lingxi;

import android.app.Application;

import com.gavin.lingxi.common.utils.DeviceUtils;
import com.puppy.bingo.tools.ProcessUtils;

import org.mym.plog.DebugPrinter;
import org.mym.plog.PLog;
import org.mym.plog.config.PLogConfig;
import org.mym.plog.printer.FilePrinter;

import java.io.File;
import java.io.FilenameFilter;
import java.text.SimpleDateFormat;
import java.util.Locale;


public class LingxiApplication extends Application {
    private final static String TAG = "BingoApplication";
    private static LingxiApplication instance;

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        boolean isMain = ProcessUtils.isMainProcess(this);
        if (isMain) {
            initPLog();
            WertcSdk.initialize(this);
        }
    }


    private void initPLog() {
        PLog.init(PLogConfig.newBuilder()
                .forceConcatGlobalTag(false)
                .globalTag("PLog")
                .useAutoTag(false)
                .needLineNumber(true)
                .needThreadInfo(true)
                .build());
        DebugPrinter debugPrinter = new DebugPrinter(true, 1024);
        PLog.appendPrinter(debugPrinter);
        String logPath = DeviceUtils.SD_CARD_ROOT + File.separator + "bingo" + File.separator + "logs";
        FilePrinter filePrinter = new FilePrinter(LingxiApplication.this, logPath, new GingoFileNameGenerator(), 4 * 1024 * 1024);
        PLog.appendPrinter(filePrinter);
    }


    public static LingxiApplication getInstance() {
        return instance;
    }


    private static class GingoFileNameGenerator implements FilePrinter.FileNameGenerator {

        private static final String formatStr = "yyyyMMdd";
        private static final String FORMAT_REGEX = "\\d{8}";
        private static final String CONCAT = "-";
        private SimpleDateFormat timingFormat = new SimpleDateFormat(formatStr, Locale.US);

        @Override
        public String nextFile() {
            return timingFormat.format(System.currentTimeMillis()) + ".log";
        }

        @Override
        public String nextFileIfDuplicate(File dir, String timestamp) {
            File[] files = dir.listFiles(new FilenameFilter() {
                @Override
                public boolean accept(File dir, String name) {
                    return name.matches(FORMAT_REGEX + CONCAT + "\\d+" + "\\.log");
                }
            });
            if (files == null || files.length == 0) {
//                throw new RuntimeException("File name not valid but no such file exists.");
                return formatNameWithSerialNum(timestamp, 1);
            }

            //Find last file and
            long lastModifiedTime = 0;
            File lastModifiedFile = null;
            for (File file : files) {
                if (lastModifiedFile == null || file.lastModified() > lastModifiedTime) {
                    lastModifiedTime = file.lastModified();
                    lastModifiedFile = file;
                }
            }
            //Must be not null
            //noinspection ConstantConditions
            String last = lastModifiedFile.getName();
            //Because we used FilenameFilter, so can be sure that suffix must be a number.
            PLog.e("last: " + last + ", len: " + (formatStr + CONCAT).length());
            int serialNum = Integer.parseInt(last.substring((formatStr + CONCAT).length()));
            return formatNameWithSerialNum(timestamp, serialNum + 1);
        }

        private String formatNameWithSerialNum(String timestamp, int serialNum) {
            return timestamp + CONCAT + serialNum + ".log";
        }
    }
}
